/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.tapestry.elfinder.util;

import java.io.File;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.activation.MimetypesFileTypeMap;

import org.apache.commons.io.FilenameUtils;

import eu.medsea.mimeutil.MimeType;
import eu.medsea.mimeutil.MimeUtil;

/**
 * @author Martin Papy
 *
 */
public class FilesUtils {
	public static final String FILE_SEPARATOR = System.getProperty("file.separator");
	
	public static AtomicBoolean isRegisterNeeded = new AtomicBoolean(true);
	
	private FilesUtils(){}
	
	public static String cleanFileName(String fileName, boolean makeUnique) {
		if(makeUnique) {
			String ext = FilenameUtils.getExtension(fileName);
			return UUID.randomUUID().toString().toLowerCase() + "." + ext;
		}
		return fileName.replaceAll("([a-z][A-Z]-_\\.)+", "_");
	}
	
	public static String sanitiseDirPath(String dirPath) {
		String path = dirPath.trim();
		
		if(path.startsWith("file://")){
			path = path.substring("file://".length());
		}
		
		if (!path.endsWith(FILE_SEPARATOR)) {
			path += FILE_SEPARATOR;
		}

		File dir = new File(path);

		if (!dir.exists()) {
			dir.mkdirs();
		}

		return path;
	}
	
	@SuppressWarnings("unchecked")
	public static String getMimeType(File file) {
		if(isRegisterNeeded.getAndSet(false)){
			MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
			MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.ExtensionMimeDetector");			
		}
		
		Collection<MimeType> mimes = MimeUtil.getMimeTypes(file);

		if (!mimes.isEmpty()) {
			return MimeUtil.getMostSpecificMimeType(mimes).toString();
		}
		
		//Fallback method
		return new MimetypesFileTypeMap().getContentType(file); 
	}
	
}
